<?php

namespace App\Models;

use App\Http\Controllers\PaymentController;
use App\Http\Controllers\WxPayController;
use App\Service\Push;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Mrgoon\AliSms\AliSms;

class AfterSales extends Model
{
    //售后管理
    protected $table ="c_after_sales";
    protected $guarded = ['im_username'];
    public function setImagesAttribute($gallery)
    {
        if (is_array($gallery)) {
            $this->attributes['images'] = json_encode($gallery);
        }
    }
    public function getImagesAttribute($gallery)
    {
        return json_decode($gallery, true);
    }

    public function order()
    {
        return $this->hasOne('App\Models\Order', "id", "order_id");
    }
   public function address()
    {
        return $this->hasOne('App\Models\AfterAddress',"after_id" ,"id");
    }

    public function ordergoods()
    {
        return $this->hasOne('App\Models\OrderGoods', "id", "order_goods_id");
    }

    /**
     * @param $data
     * @return bool|string
     * 申请售后
     */
    public function addAfterSales($data)
    {
        try {
            DB::beginTransaction(); // 开始事务
            if (isset($data['id']) && !empty($data['id'])) {
                $detail = $this->getAfterSalesDetail($data['id']);
                if ($detail->status == 2) {
                    $detail->after_type = isset($data['after_type']) ? $data['after_type'] : $detail->after_type;
                    $detail->order_id = isset($data['order_id']) ? $data['order_id'] : $detail->order_id;
                    $detail->order_sn = isset($data['order_sn']) ? $data['order_sn'] : $detail->order_sn;
                    $detail->goods_status = isset($data['goods_status']) ? $data['goods_status'] : $detail->goods_status;
                    $detail->goods_num = isset($data['goods_num']) ? $data['goods_num'] : $detail->goods_num;
                    $detail->back_reason = isset($data['back_reason']) ? $data['back_reason'] : "";
                    $detail->money = isset($data['money']) ? $data['money'] : $detail->money;
                    $detail->coupon_id = isset($data['coupon_id']) ? $data['coupon_id'] : $detail->coupon_id;
                    $detail->address_id = isset($data['address_id']) ? $data['address_id'] : $detail->address_id;
                    $detail->images = isset($data['images']) ? Tool::handelString($data['images']): $detail->images;
                    $detail->describe = isset($data['describe']) ? $data['describe'] : $detail->describe;
                    $detail->logis_company = isset($data['logis_company']) ? $data['logis_company'] : $detail->logis_company;
                    $detail->logis_num = isset($data['logis_num']) ? $data['logis_num'] : $detail->logis_num;
                    $detail->logis_code = isset($data['logis_code']) ? $data['logis_code'] : $detail->logis_code;
                    $state = $detail->save();
                    if ($state) {
                        if(isset($data['address_id'])){
                            (new AfterAddress())->add($data['address_id'],$data['id']);
                        }
                        DB::commit();
                        return true;
                    } else {
                        DB::rollBack();
                    }
                }
                if ($detail->status === 0) {
                    return "该售后正在审核中,请耐心等待";
                }
                if ($detail->status == 1) {
                    return "该售后已审核通过,不能修改售后信息";
                }

            } else {
                $orders = (new Order())::getOrderDetail($data['order_id']);
                if (empty($orders)) {
                        return "该订单不存在!";
                }
                $after = $this->where([['order_id','=',$data['order_id']]])->first();
                if (!empty($after)) {
                    (new AfterAddress())->del($after->id);
                    $this->where([['order_id', '=', $data['order_id']]])->delete();
                }
//                if (!empty($orders)) {
//                    if ($orders->order_status == 2) {
//                        return "该订单已经申请过售后,不能重复申请!";
//                    }
//                }
                $goods_info = (new ProductGoods())->where([['id','=',$orders->ordergoods[0]->goods_id]])->first();
                if($goods_info->product_source ==1){
                    $this->order_source = 1;
                    $this->work_id = $goods_info->supplier_work_id;
                    //工作室人员名称
                    $dot = (new Doctor())->where([["work_id",'=',$goods_info->supplier_work_id],["is_admin","=",1]])->first();//value("account");
                    $doc_name = $dot->real_name; //$orders->ordergoods[0]->goods_name;
                    $call =$dot->account;
                }else{
                    $this->order_source = 2;
                    $this->suppliers_id = $goods_info->supplier_work_id;
                    $sup = (new AdminUser())->where([["id","=",$goods_info->supplier_work_id]])->first();
                    $doc_name = $sup->name;
                    $call = $sup->username;
                }
                $this->after_type = isset($data['after_type']) ? $data['after_type'] : "";
                $this->order_id = isset($data['order_id']) ? $data['order_id'] : "";
                $this->order_goods_id = $orders->ordergoods[0]->id;
                $this->order_sn = isset($data['order_sn']) ? $data['order_sn'] : "";
                $this->goods_status = isset($data['goods_status']) ? $data['goods_status'] : "";
                $this->goods_num = isset($data['goods_num']) ? $data['goods_num'] : "";
                $this->back_reason = isset($data['back_reason']) ? $data['back_reason'] : "";
                $this->money = isset($data['money']) ? $data['money'] : "";
                $this->coupon_id = isset($data['coupon_id']) ? $data['coupon_id'] : "";
                $this->address_id = isset($data['address_id']) ? $data['address_id'] : "";
                $this->images = isset($data['images']) ? Tool::handelString($data['images']) : "";
                $this->describe = isset($data['describe']) ? $data['describe'] : "";
                $this->logis_company = isset($data['logis_company']) ? $data['logis_company'] : "";
                $this->logis_num = isset($data['logis_num']) ? $data['logis_num'] : "";
                $this->logis_code = isset($data['logis_code']) ? $data['logis_code'] : "";
                $res = $this->save();
                if ($res) {
                    $up_res = (new Order())->where([['id', '=', $data['order_id']]])->update(['order_status' => 2]);
                    if ($up_res) {
                        if(isset($data['address_id'])){
                            (new AfterAddress())->add($data['address_id'],$this->id);
                        }
                        //发送短信工作室或者供应商
                        $ali_sms = new AliSms();
                        $paras['unit_name'] = $doc_name;
                        //给用户发送短信
                        $ali_sms::sendMessage($call,$paras,5);
                        //发推送消息
                        $push = new Push();
                        $doc = (new Doctor())->where([['work_id', '=', $orders->work_id],['is_admin','=',1]])->first();
                        $lt['type'] = 2;
                        $lt['user_id'] = $doc->id;
                        $lt['title'] = "申请售后消息";
                        $lt['content'] = "有用户在您工作室购买的商品申请了售后，请您留意并及时处理。";
//                        $push->pushToUser($lt);
                        DB::commit();
                        return true;
                    }
                }
                DB::rollBack();
                return "申请失败!";
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /**
     * @param $id
     * @return mixed
     * 获取售后详情
     */
    public function getAfterSalesInfo($id)
    {
        $res =  $this->with(["order",'address',"ordergoods"])->where([['id','=',$id]])->first();
        $tool = new Tool();
        $area = new Area();
        $host = new Url();
        if($res){
            $ts["type"] = 1;
            $ts["user_id"] = $res->order->user_id;
            $im = Tool::getUserNameForIm($ts);
            $res->im_username = $im['username'];
            $res->images = $tool->addHostToImage($res->images);
            $res->ordergoods->goods_img =$host::getHttpHost().'upload/'. $res->ordergoods->goods_img;
            if(!empty($res->address)){
                $res->address->province =$area::getNameByCode($res->address->province_id);
                $res->address->city =$area::getNameByCode($res->address->city_id);
                $res->address->district =$area::getNameByCode($res->address->district_id);
            }
        }
        return $res;
    }

    public function getAfterSalesDetail($id)
    {
        $res = $this->with(["order", 'address', "ordergoods"])->where([['id', '=', $id]])->first();
        return $res;
    }


    /***
     * @param $id
     * 拒绝收货
     */
    public function doRejectReason($filter)
    {
        $after_info = $this->getAfterSalesDetail($filter['after_id']);
        //查看商品是否是工作室商品
//        $order = (new Order())->where([['id','=',$after_info->order_id]])->first();
//        if($order->order_source == 2){
//            return "该订单供应商产品订单,无权";
//        }
        $after_info->status = 2;
        $after_info->reject_reason = $filter['reject_reason'];
        return $after_info->save();
    }

    /***
     * @param $id
     * 同意售后
     */
    public function doAgree($filter)
    {
        $after_info = $this->getAfterSalesDetail($filter['after_id']);
        if ($after_info->order_source == 2) {
            return "该商品为供应商产品,需要供应商操作退款!";
        }
        if ($after_info->after_status == 1) {
            return "该订单售后已完成!";
        }
//        判断售后类型
//        if($after_info->after_type == 1){ //仅退款
//            退款操作
            if ($after_info->order->pay_type == 1) { //微信支付
                $da['sn'] = $after_info->order->sn;
                $da['return_sn'] = (new Order())->orderNumber();
                $da['price'] =$after_info->order->pay_price;
                (new WxPayController())->returnBack($da);
                return true;
//                if($bk =='退款成功'){
//                    $back = true;
//                }else{
//                    return $bk;
//                }
            } elseif ($after_info->order->pay_type == 2) { //支付宝
                $da['sn'] = $after_info->order->sn;
                $da['back_sn'] = (new Order())->orderNumber();
                $da['money'] =$after_info->order->pay_price;
                $back = (new PaymentController())->doReturn($da);
                if($back !== true){
                    return "退款失败,请稍后再试!";
                }
            }
            if ($back ===true) {  //如果退款成功
                //退回账单记录
                (new FinancialStatementsLog())->setAfterAgreeGoodsOrderBack($after_info->order_id);
//            修改订单
                $lit['order_status'] = 3;
                (new Order())->where([['id', '=', $after_info->order_id]])->update($lit);
                //修改售后订单
                $after_info->after_status = 1;
                $after_info->status = 1;
                return $after_info->save();
            }
//        }
//        elseif ($after_info->after_type == 2){ //退货退款
//            $after_info->status = 1;
//            return $after_info->save();
//        }
    }

    /***
     * @param $filter
     * @return mixed
     * 添加物流
     */
    public function addLogisNum($filter)
    {
        $after = $this->where([['id', '=', $filter['after_id']]])->first();
        $after->logis_code = $filter['logis_code'];
        $after->logis_company = $filter['logis_company'];
        $after->logis_num = $filter['logis_num'];
        return $after->save();
    }
    
    
}
